//
//  MLStatusViewModel.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/9.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit
import SDWebImage

private let imageMargin:CGFloat = 2
private let imageMax:CGFloat = screenW - 2*margin
let imageWidth:CGFloat = (imageMax-2*imageMargin)/3

class MLStatusViewModel: NSObject {
    
    
    var iconURL:URL?
    
    var mbankImage: UIImage? //登记
    
    var verifitedImage: UIImage? //认证
    
    var collectionViewSize:(CGSize,CGSize) = (CGSize.zero,CGSize.zero)
    
    /// 转发的或者原生的图片数组
    var all_pic_urls:[MLPictureInfo]?
    
    //来源
    var sourceText:String? {
    
        didSet{ //<a href=\"http://weibo.com/\" rel=\"nofollow\"> 榜姐的iPhone</a>
        
//            print("sourceText:::",sourceText)
        
            let statrFlag = "\">"
            let endFlag = "</a>"
            
            guard let startRange = sourceText?.range(of: statrFlag) ,
                  let endRange   = sourceText?.range(of: endFlag) else {
                
//                print("来自火星")
                return
            }
            
            
            let range = startRange.upperBound ..< endRange.lowerBound
            
            sourceText = "来自" + (sourceText?.substring(with: range) ?? "")
        }
    }
    
    
    //时间
    var timeTex:String? {
    
        didSet{
            //"Wed Jan 11 23:21:21 +0800 2017"
            
            //1.实例化日期格式化对象
            let dateFormater = DateFormatter()
            
            //2.指定格式化符
            dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
            //在真机上必须设置本地化信息否则转换失败
            dateFormater.locale = Locale(identifier: "en")
            //3.将字符串转换日期对象
            let sinaDate = dateFormater.date(from: timeTex!)!
            let currentDate = Date()
            
//            print(sinaDate) //2017-01-11 15:31:27 +0000
            //4.处理日期
            let calendar = Calendar.current
            let result = calendar.dateComponents([.year,], from: sinaDate, to: currentDate)
            
            if result.year == 0 { //今年
                
                //是否今天
                if calendar.isDateInToday(sinaDate) {
                    
                    //获取当前时间和sinaDate秒的差值
                    let delta = Date().timeIntervalSince(sinaDate)
                    
                    if delta < 60 { //一分钟内
                        
                        timeTex =  "刚刚"
                    }else if delta < 3600 { //几分钟前
                    
                        
                        timeTex =  "\(Int(delta/60))分钟前"
                        
                    }else{
                        
                        timeTex =  "\(Int(delta/3660))分钟前"
                    }
                    
                    
                    //是否昨天

                }else if calendar.isDateInYesterday(sinaDate) {
                
                    dateFormater.dateFormat = "昨天 HH:mm"
                    
                    timeTex = dateFormater.string(from: sinaDate)
                    
                }else{
                
                    dateFormater.dateFormat = "MM-dd HH:mm"
                    
                    timeTex = dateFormater.string(from: sinaDate)
                }
            }else{ //其他年
            
                dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
                
                timeTex = dateFormater.string(from: sinaDate)
            }
            
        }
    }
    

    
    var status:MLStatus? {
        
        didSet{
            
            if status?.retweeted_status == nil {
            
                all_pic_urls = status?.pic_urls
                
            }else{
            
                all_pic_urls = status?.retweeted_status?.pic_urls
            }
            
            iconURL =  URL(string: status?.user?.avatar_large ?? "")
            
            dealWithMbankImage()
            
            dealWithVerifitedImage()
            
            /// 计算的高度
            let tempSize = caculateCollectionViewSize()
            
            collectionViewSize = tempSize
            
            
            timeTex = status?.created_at
            sourceText = status?.source
        }
    }
    
    
    /// 返回两个，一个pictureView的大小 ，一个是item大小
    private func caculateCollectionViewSize() -> (itemSize:CGSize,imageSize:CGSize) {
        
        var count:CGFloat = 0
        
        if status?.retweeted_status == nil {
            
            count = CGFloat(status?.pic_urls?.count ?? 0)
            
        }else{
            
            count = CGFloat(status?.retweeted_status?.pic_urls?.count ?? 0)
        }
        
        
//        print("数组个数:::",status?.pic_urls?.count ?? 0)
        
        if count==0 {
            
            return  (CGSize(width: 1, height: 1),CGSize(width: 1, height: 1))
        }
        
        if count == 1 {
         
            //TODO: 取出一张图片，获取size
          let image =   SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: all_pic_urls?.last?.wap360)
        
            
            let imageSize = image?.size ?? CGSize.zero
            
            return (CGSize(width: imageSize.width, height: imageSize.height),CGSize(width: imageSize.width, height: imageSize.height))
        }
        
        if count==4 {
            
            let w = imageWidth*2 + imageMargin
            
            return (CGSize(width: w, height: w), CGSize(width: imageWidth, height: imageWidth))
        }
        
        let row:Int = Int((count-1)/3)+1
        let w = imageMax
        let h = CGFloat(row) * imageWidth + CGFloat(row-1)*imageMargin
//        print("此处注意:::",row,count,imageWidth,w,h)

        return (CGSize(width: w, height: h),CGSize(width: imageWidth, height: imageWidth))
    }
    
    
    private func dealWithMbankImage() {
        
        let remark = status?.user?.mbrank ?? 0
        
        if remark>0 && remark<7 {
            
            mbankImage = UIImage(named: "common_icon_membership_level\(remark)")
            
        }
    }
    
    private func dealWithVerifitedImage() {
        
        //微博认证的图片
        let type = status?.user?.verified_type ?? -1
        
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
            
        default:
            //没有认证
            verifitedImage = nil
        }
        
    }
    
    
}
